<template>
  <div class="baseinfo" style="padding-bottom: 70px">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{ form.projectNo }}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="请输入有效的项目名称"  
               :disabled="form.status>1"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="项目分类"
            prop="projectTypeSubCategory"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.projectTypeSubCategory"
              placeholder="请选择项目分类"
              :options="projectCategoryOptions" :disabled="form.id!=''"  
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            ref="hatchProjectNo"
            label="动议项目编号"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.hatchProjectNo" placeholder="点击选择动议项目" @click="hatch.visible = true"   :disabled="form.status>1"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="16">
          <a-form-model-item
            ref="hatchProjectName"
            label="动议项目名称"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 19 }"
          >
            <a-input v-model="form.hatchProjectName" placeholder="点击选择动议项目" @click="hatch.visible = true"  :disabled="form.status>1"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            ref="workshop"
            label="二化车间"
            prop="workshop"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.workshop"
              @blur="
                () => {
                  $refs.workshop.onFieldBlur()
                }
              "
              placeholder="请输入有效的二化车间"  
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="post"
            label="二化岗位"
            prop="post"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.post"
              @blur="
                () => {
                  $refs.post.onFieldBlur()
                }
              "
              placeholder="请输入有效的二化岗位"  
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="quantity"
            label="岗位数量"
            prop="quantity"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.quantity"
              type="number" min="0" max="100000"
              @blur="
                () => {
                  $refs.quantity.onFieldBlur()
                }
              "
              placeholder="请输入有效的岗位数量"  
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="postStatus"
            prop="postStatus"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            class="slot-label"
          >
            <span slot="label">岗位现状<p>(500字内)</p></span>
            <a-textarea
              v-model="form.postStatus"
              @blur="
                () => {
                  $refs.postStatus.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="(500字内)"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <br/>
      <h3 style="font-weight:bold;margin-left:20px;">二化原因:</h3>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="机械化"
            prop="mechanization"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              mode="multiple" 
              v-model="mechanization"
              placeholder="请选择机械化"
              :options="mechanizationOptions"
              @change="mechanizationChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="信息化"
            prop="informationize"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              mode="multiple" 
              v-model="informationize"
              placeholder="请选择信息化"
              :options="informationizeOptions"
              @change="informationizeChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="landingMethod"
            label="二化落地方法"
            prop="landingMethod"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <a-select
              mode="multiple" 
              v-model="landingMethod"
              placeholder="请选择二化落地方法"
              :options="landingMethodyOptions"
              @change="landingMethodChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="implementationPlan"
            prop="implementationPlan"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            class="slot-label"
          >
            <span slot="label">实施方案简述<p>(500字内)</p></span>
            <a-textarea
              v-model="form.implementationPlan"
              @blur="
                () => {
                  $refs.implementationPlan.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
              placeholder="(500字内)"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="expectedTarget"
            prop="expectedTarget"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            class="slot-label"
          >
            <span slot="label">预期目标<p>(500字内)</p></span>
            <a-textarea
              v-model="form.expectedTarget"
              @blur="
                () => {
                  $refs.expectedTarget.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 6, maxRows: 8 }"
              style="width: 100%"
              placeholder="1、技术创新目标：
2、生产效率变化：
3、质量提升作用：（杂质控制、减少人为操作、质量信息可溯源、可质量分析等方面的提升）
4、岗位安全改善：（含操作安全、设备安全、岗位危害因素、岗位保密等改善或革新）
5、岗位减员情况：
6、其他如有……(500字内)"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <five-to-five ref="fiveForm" :projectBuildId="projectBuildId" :change-id="changeId" @addField="addFiveDataToForm"/>
      <div>
        <div class="info-title">
          <span>数字贷信息</span>
        </div>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item
              label="是否数字贷"
              ref="digitalLoan"
              prop="digitalLoan"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-radio-group v-model="form.digitalLoan" @change="handleDigitalLoanChange">
                <a-radio :value="true"> 是 </a-radio>
                <a-radio :value="false"> 否 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="form.digitalLoan">
            <a-form-model-item
              label="备案证名称"
              prop="filingName"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-select
                v-model="form.filingName"
                placeholder="请选择"
                :options="filingNameOptions"
              >
                <a-icon slot="suffixIcon" type="plus" />
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
    </a-form-model>

    <pagination-select
      :title="hatch.title"
      :searchPlaceholder="hatch.searchPlaceholder"
      :visible="hatch.visible"
      :url="hatch.url"
      :columns="hatch.columns"
      @hatchHandleOk="hatchHandleOk"
    />
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import Vue from 'vue'
export default {
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive')
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    },
    selProjectType: {
      Type: String,
      default: '',
    }
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      subName: '',
      form: {
        id: '',
        projectClass: '41',
        projectNo: '',
        projectName: '',
        mainDeptName: '',
        projectTypeSubCategory: '',
        hatchProjectId: '',
        hatchProjectNo: '',
        hatchProjectName: '',
        workshop: '',
        post: '',
        quantity: '',
        postStatus: '',
        mechanization: undefined,
        informationize: undefined,
        landingMethod: undefined,
        implementationPlan: '',
        expectedTarget: ''
      },
      rules: {
        projectName: [
          { required: true, message: '请输入有效的项目名', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        projectContent: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目概述不超过500个字符', trigger: 'blur' },
        ],
        workshop: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 120, message: '项目概述不超过500个字符', trigger: 'blur' },
        ],
        post: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 120, message: '项目概述不超过500个字符', trigger: 'blur' },
        ],
        quantity: [
          { required: true, message: '请输入项目概述', trigger: 'blur' }
        ],
        postStatus: [
          { required: true, message: '请输入岗位现状', trigger: 'blur' },
          { min: 1, max: 500, message: '岗位现状不超过500个字符', trigger: 'blur' },
        ],
        landingMethod: [{ required: true, message: '请选择二化落地方法', trigger: 'change' }],
        implementationPlan: [
          { required: true, message: '请输入实施方案简述', trigger: 'blur' },
          { min: 1, max: 500, message: '实施方案简述不超过500个字符', trigger: 'blur' },
        ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        expectedTarget: [
          { required: true, message: '请输入预期目标', trigger: 'blur' },
          { min: 1, max: 500, message: '预期目标不超过500个字符', trigger: 'blur' },
        ],
        digitalLoan:[
          { required: true, message: '请选择是否数字贷', trigger: 'change' }
        ],
        filingName: [
        ],
      },
      projectCategoryOptions: [],
      mechanizationOptions: [],
      informationizeOptions: [],
      landingMethodyOptions: [],
      mechanization: undefined,
      informationize: undefined,
      landingMethod: undefined,
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
      },
      hatch: {
        visible: false,
        title: '请选择孵化项目',
        searchPlaceholder: '输入代码或名称查询',
        url: '/hatchProject/listBySelect',
        columns: [
          {
            title: '孵化项目编号',
            dataIndex: 'hatchProjectNo',
            align: 'center',
          },
          {
            title: '孵化项目名称',
            dataIndex: 'hatchProjectName',
            align: 'center',
          },
        ],
      },
      loadFinish: false,
      filingNameOptions: [],
      filingNameRule:{ required: true, message: '请选择备案证名称', trigger: 'change' }
    }
  },
  computed: {},
  methods: {
    addFiveDataToForm(val,valRef) {
      this.$set(this.form, valRef, val)
    },
    handleDigitalLoanChange(){
      if(this.form.digitalLoan){
        this.rules.filingName.push(this.filingNameRule);
      }else{
        this.rules.filingName=[];
      }
    },
    async doSubmit() {
      if(!this.loadFinish){
        layer.message.warning('请等待页面加载完毕')
        return {}  
      }
      var validR = false
      try {
        validR = await this.$refs.ruleForm.validate()
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      } catch (e) {
        validR = false
      }
      console.log('validR', validR)
      this.form.validResult = validR
      let res = await this.doSave()
        this.projectBuildId=res;
      return { valid: validR, id: res }
    },
    async doSave() {
      let flag = null
      var formData = JSON.parse(JSON.stringify(this.form))
      if (formData.designSource!=null && formData.designSource.length>0) {
        formData.designSource = formData.designSource.join(',');
      } else {
        formData.designSource = ''
      }
      formData.changeId=this.changeId;
      var vm = this
      await postActionAsync(this.url.save, formData)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id
            vm.form.projectNo = res.result.projectNo
            this.$message.success('保存成功')
            return (flag = res.result.id)
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
      return flag
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass,pageSize:-1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })

              if (vm.projectCategoryOptions.length === 1) {
                vm.form.projectTypeSubCategory = vm.projectCategoryOptions[0].value
              }
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
//初始化项目所属的品类
    initFilingNameOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '数字贷备案证名称' })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.filingNameOptions.push({ value: item.name, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询数字贷备案证名称失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询数字贷备案证名称失败:' + res.message)
        })
    },
    //孵化项目选中
    hatchHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.hatchProjectId = record[0].id
        this.form.hatchProjectNo = record[0].hatchProjectNo
        this.form.hatchProjectName = record[0].hatchProjectName
      }
      this.hatch.visible = false
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId,changeId:this.changeId })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                if (this.form.mechanization) {
                  this.mechanization = this.form.mechanization.split(',');
                }
                if (this.form.informationize) {
                  this.informationize = this.form.informationize.split(',');
                }
                if (this.form.landingMethod) {
                  this.landingMethod = this.form.landingMethod.split(',');
                }
                //this.initSubName()
                this.handleDigitalLoanChange();
                this.loadFinish=true;
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      }else{
        this.loadFinish = true;
      }
    },
    initSubName () {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0,parentid:vm.form.projectClass,code:vm.form.projectType})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
    mechanizationChange(value){
      this.$set(this.form,'mechanization',value.join(","));
    },
    informationizeChange(value){
      this.$set(this.form,'informationize',value.join(","));
    },
    landingMethodChange(value){
      this.$set(this.form,'landingMethod',value.join(","));
    },
    initTcodeInfoOptions () {
      var vm = this
      getAction(this.url.codeInfoList, { type: '二化机械化原因', pageNo:1,pageSize:9999,isdel: 0 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {

              list.records.sort(function(obj1,obj2){
                return parseInt(obj1.code)-parseInt(obj2.code);
              })
              list.records.map((item) => {
                vm.mechanizationOptions.push({ value: item.code, label: item.name })
              })
              // vm.mechanizationOptions.sort(function(obj1,obj2){
              //   return parseInt(obj1.code)-parseInt(obj2.code);
              //   // var val1 = obj1.code;
              //   // var val2 = obj2.code;
              //   // if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
              //   //     val1 = Number(val1);
              //   //     val2 = Number(val2);
              //   // }
              //   // if (val1 < val2) {
              //   //     return 1;
              //   // } else if (val1 > val2) {
              //   //     return -1;
              //   // } else {
              //   //     return 0;
              //   // } 
              // })
            }
          } else {
            this.$message.warning('查询二化机械化原因失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询二化机械化原因失败:' + res.message)
        })

        getAction(this.url.codeInfoList, { type: '二化信息化原因', pageNo:1,pageSize:9999,isdel: 0 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.sort(function(obj1,obj2){
                return parseInt(obj1.code)-parseInt(obj2.code);
              })
              list.records.map((item) => {
                vm.informationizeOptions.push({ value: item.code, label: item.name })
              })
              // vm.informationizeOptions.sort(function(obj1,obj2){
              //                   return parseInt(obj1.code)-parseInt(obj2.code);

              //   // var val1 = obj1.code;
              //   // var val2 = obj2.code;
              //   // if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
              //   //     val1 = Number(val1);
              //   //     val2 = Number(val2);
              //   // }
              //   // if (val1 < val2) {
              //   //     return 1;
              //   // } else if (val1 > val2) {
              //   //     return -1;
              //   // } else {
              //   //     return 0;
              //   // } 
              // })
            }
          } else {
            this.$message.warning('查询二化信息化原因失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询二化信息化原因失败:' + res.message)
        })

        getAction(this.url.codeInfoList, { type: '二化落地方法', pageNo:1,pageSize:9999,isdel: 0 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.sort(function(obj1,obj2){
                return parseInt(obj1.code)-parseInt(obj2.code);
              })
              list.records.map((item) => {
                vm.landingMethodyOptions.push({ value: item.code, label: item.name })
              })
              // vm.landingMethodyOptions.sort(function(obj1,obj2){
              //                   return parseInt(obj1.code)-parseInt(obj2.code);

              //   // var val1 = obj1.code;
              //   // var val2 = obj2.code;
              //   // if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
              //   //     val1 = Number(val1);
              //   //     val2 = Number(val2);
              //   // }
              //   // if (val1 < val2) {
              //   //     return 1;
              //   // } else if (val1 > val2) {
              //   //     return -1;
              //   // } else {
              //   //     return 0;
              //   // } 
              // })
              // vm.landingMethodyOptions = Object.assign({}, vm.landingMethodyOptions)
            }
          } else {
            this.$message.warning('查询二化落地方法失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询二化落地方法失败:' + res.message)
        })
    }
  },
  mounted() {

    // if (this.projectBuildId == null || this.projectBuildId == '') {
    //     this.form.projectType = this.selProjectType
    //     this.form.projectTypeSubCategory = this.selProjectType
    //     this.initSubName()
    //   }
    this.initProjectCategoryOptions()
    this.initTcodeInfoOptions()
    this.initFilingNameOptions();
    this.initData()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
</style>